package com.astersoft.lib.net;

/*
 * Copyright 2012 AsterSoft personal developer - Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.StringTokenizer;

import com.astersoft.lib.ASMiscellaneaUtil;

/**
 * 
 * @author dario.durzo
 * @version 0.1
 * @created.date 2009.08.26
 */
public class ASNetUtils {
	public static byte[] getMAC(){
		byte[] mac = null;
		String className = null;
		if(ASMiscellaneaUtil.getJVMVersion() >= (float) 1.6) {
			className = "com.astersoft.lib.net.impl.ASNet6";
		} else {
			className = "com.astersoft.lib.net.impl.ASNet5";
		}
		
		Class<?> ntClass;
		try {
			ntClass = Class.forName(className);
		    Method method = ntClass.getDeclaredMethod("getMac");
		    mac = (byte[])method.invoke(null);
		} catch (Exception e) {
		    e.printStackTrace();
		} 
		
		return mac;
	}
	
	/**
	 * This function gets a file from a server location through a URL connection
	 * (http or ftp)
	 * 
	 */
	public static void downloadFileFromURL(String url, String dir) {
		URL fileToGetURL = null;
		long total_bytes = 0;

		try {
			fileToGetURL = new URL(url);
		} catch (MalformedURLException mue) {
			System.out.println("Error: " + mue);
		}

		File test_dir = new File(dir);

		if (!test_dir.exists() || !test_dir.isDirectory()) {
			System.out.println("Directory " + dir
					+ " does not exist or is not a directory.");
			return;
		}

		String filename = fileToGetURL.getFile();

		int index = filename.lastIndexOf('/'); // take out any leading path dirs
		if (index != -1)
			filename = filename.substring(index + 1);

		String fileToWrite = new StringBuffer(dir).append(File.separator)
				.append(filename).toString();

		// now try to download the file
		try {
			URLConnection conn = fileToGetURL.openConnection();
			int content_length = conn.getContentLength();

			DataInputStream fileToGetStream = new DataInputStream(
					conn.getInputStream());
			BufferedInputStream bis = new BufferedInputStream(fileToGetStream);
			FileOutputStream fos = new FileOutputStream(fileToWrite);

			int N = 1024;
			byte buf[] = new byte[N];
			int ln = 0;
			int int_len = -1;

			System.out.println("File size: " + content_length + " bytes. ");
			System.out.print("Percent downloaded: ");

			while ((ln = bis.read(buf, 0, N)) != -1) {
				fos.write(buf, 0, ln);
				total_bytes += ln;

				if (int_len != -1) {
					System.out.print("\b"); // to get rid of the percentage sign
					for (int i = 0; i < int_len; i++)
						System.out.print("\b");
				}

				long percentage = (total_bytes * 100) / (long) content_length;
				int_len = Long.toString(percentage).length();
				System.out.print(percentage + "%");
			}

			fos.flush();
			fos.close();
			bis.close();
			fileToGetStream.close();

		} catch (FileNotFoundException fnfe) {
			System.out.println("Error " + fnfe + ": file " + filename
					+ " not found.");
		} catch (IOException ioe) {
			System.out.println("Error: " + ioe);
		}

		System.out.println("\n" + total_bytes + " bytes of file " + filename
				+ " downloaded.");
	}
	
	public static boolean isValidEmailAddress(String address) {
		return isValidCommonEmailAddress(address);
	}

	private static boolean isValidCommonEmailAddress(String address) {
		// Algorithm:
		// Check for existence of the @ symbol. If false, return false, else
		// proceed.
		// Separate the two tokens on the left hand and the right hand side of
		// the last
		// occurence of the@ symbol.
		// Check that the user name part ( left hand side of the @ ) is correct.
		// Check that the machine name part ( right hand side of the @ ) is
		// correct.
		// If both are true, return true, else return false.

		int symbol_index = address.lastIndexOf('@');
		if (symbol_index == -1) { // symbol not found
			return false;
		}

		String user = address.substring(0, symbol_index);
		String machine_name = address.substring(symbol_index + 1);

		return (isValidUserName(user) && ASDomainNameChecker.isLegalDomainName(machine_name));
	}

	private static boolean isValidUserName(String user) {
		// Algorithm
		// Separate the different tokens between the periods
		// Check that the tokens are valid. ( Invalid characters are
		// ()<>@,;:.[]\" )
		final String ILLEGAL_CHARS = "()<>@,;:.[]\\\"";
		boolean retVal = true;

		StringTokenizer strtok = new StringTokenizer(user, ".");
		while (strtok.hasMoreTokens()) {
			if (ASDomainNameChecker.containsCharsInSet(strtok.nextToken(),
					ILLEGAL_CHARS)) {
				retVal = false;
				break;
			}
		}

		return retVal;
	}
}
